<?php

namespace app\yperp\common;

class ArrayHelpers
{
    public static function isIndexed($array, $consecutive = false)
    {
        if (!is_array($array)) {
            return false;
        }

        if (empty($array)) {
            return true;
        }

        if ($consecutive) {
            return array_keys($array) === range(0, count($array) - 1);
        }

        $is = true;
        foreach ($array as $key => $value) {
            if (!is_int($key)) {
                $is = false;
            }
            if ($key == "0") {
                $is = true;
            }
        }

        return $is;
    }
    public static function getTabs($num)
    {
        $tabs = "";
        for ($i = 1; $i <= $num; $i++) {
            $tabs .= "    ";
        }
        return $tabs;
    }

    protected static function echoArrayContent(array $array, $delFileds = [], $tabs = 0, $isOne = true)
    {
        $tabs++;
        echo static::getTabs($tabs) . "[" . "\r\n";
        foreach ($array as $key => $item) {
            if (is_array($item)) {
                
                echo static::getTabs($tabs) . '"' . $key . '" => [' . "\r\n";
                if (static::isIndexed($item)) { //索引数组

                    foreach ($item as $k => $v) {
                        if (is_array($v)) {

                            static::echoArrayContent($v, $delFileds, $tabs, false);

                        } else {

                            echo (is_numeric($v) ? $v : '"' . $v . '"');

                            if ($k != count($item) - 1) {
                                echo ",";
                            }
                        }
                    }

                } else { //关联数组
                    static::echoArrayContent($item, $delFileds, $tabs, false);
                }
                echo static::getTabs($tabs) . "],\r\n";
            } else {
                if (in_array($key, $delFileds)) {
                    continue;
                }else{
                    $val = is_numeric($item) ? $item : '"' . $item . '"';
                    echo static::getTabs($tabs) . '"' . $key . '" => ' . $val . ",\r\n";
                }
               
            }
        }
        if ($isOne) {
            echo static::getTabs($tabs) . "];\r\n";

        } else {
            echo static::getTabs($tabs) . "],\r\n";
        }
    }

    public static function getArrayContent(array $array,array $delFileds = [], $clear = false)
    {
        ob_start();
        static::echoArrayContent($array, $delFileds);
        $str = ob_get_clean();
        if ($clear) {
            $array = explode("\r\n", $str);
            if ($array[1] == '    "0" => [') {
                unset($array[1]);
                unset($array[count($array) - 3]);
            }
            $str = join("\r\n", $array);
        }

        return $str;
    }
}
